from django.db import models


# Create your models here.
class User(models.Model):
    id = models.AutoField(primary_key=True)
    email = models.EmailField(null=True)
    name = models.CharField(max_length=30,verbose_name="姓名")
    tel = models.CharField(max_length=11,verbose_name="电话号码")
    address = models.CharField(max_length=255,verbose_name="居住地址")
    age = models.IntegerField(null=True,verbose_name="年龄")
    birthday = models.DateField(null=True,verbose_name="生日")
    username = models.CharField(max_length=10,verbose_name="账号")
    password = models.CharField(max_length=8,verbose_name="密码")
    webname = models.CharField(max_length=8,verbose_name="网名",null=True)
    collect = models.ManyToManyField('Topic', related_name='users_collect', blank=True ,verbose_name="用户收藏的话题" )
    concern = models.ManyToManyField('User', related_name='user_concern',blank=True,verbose_name="用户关注的" )
    points =  models.JSONField(null=True,verbose_name="评分")
    def get_concern_count(self):
        return self.user_concern.all().count()
    def __str__(self):
        return self.username  # 在管理界面中显示用户的用户名
    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name

class Topic(models.Model):
    title = models.CharField(max_length=30)
    content = models.TextField(null=True)
    publish_time = models.DateTimeField(auto_now_add=True)
    topic_type = models.CharField(max_length=50)
    publisher = models.ForeignKey(User,on_delete=models.CASCADE)  # 设置外键关联User模型
    likes_number = models.IntegerField(null=True)  #赞同
    dislikes_number = models.IntegerField(null=True)  #不赞同
    is_featured = models.BooleanField(default=False,verbose_name="是否是特色主题",null=True)
    class Meta:
        verbose_name = '话题'
        verbose_name_plural = verbose_name
    def __str__(self):
        # return self.title,self.publisher\
        return f'{self.title} - {self.publisher}'

    def vote_up(self):
        # 当有人点赞时，增加点赞数
        self.likes_number += 1
        self.save()

    def vote_down(self):
        # 当有人点赞时，增加点赞数
        self.dislikes_number += 1
        self.save()
    def comment_count(self):
        # 返回该话题相关的评论数量
        return self.comment_set.count()


class Comment(models.Model):
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField()
    likes_number = models.IntegerField(default=0)  # 默认点赞数为0
    publish_time = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return f'{self.user.username} 对话题 "{self.topic.title}" 的评论'
    class Meta:
        verbose_name = '用户评论'
        verbose_name_plural = verbose_name



